import 'videojs-flash'
import 'videojs-hotkeys'
import Header from '../../components/Header.vue'
export default {
	name: 'media',
	components: {
		Header
	},
	mounted: function() {
		if (this.$route.params.companyId) {
			this.companyId = this.$route.params.companyId + "";
		}
		this.query(1);
		// 保存下初始值
		this.typeList = this.$getDictList("image_type");
		this.defaultData = JSON.parse(JSON.stringify(this.addForm));
		this.setCompanyList();
	},
	computed: {
		player: function() {
			return this.$refs.videoPlayer.player;
		}
	},
	methods: {
		setCompanyList: function() {
			let page = this;
			let userInfo = JSON.parse(localStorage.getItem("userInfo"));
			let companyId = userInfo.companyId.toString();
			this.companyName = userInfo.companyName;
			this.loading = true;
			this.axios.hPost("/api/company/query", {}, (res) => {
				page.loading = false;
				if (res.data) {
					page.companyList = page.getListByTree(res.data);
					if (!page.companyId) {
						page.companyId = companyId;
						page.query(1);
					}
				}
			});
		},

		getListByTree: function(companyTree) {
			let page = this;
			let list = [];
			companyTree.forEach(function(v) {
				list.push({
					id: v.id,
					value: v.text
				});
				if (v.children.length > 0) {
					let child = page.getListByTree(v.children);
					list = list.concat(child);
				}
			});
			return list;
		},
		getCompanyId: function() {
			this.type_query = '';
			// 公司编号
			this.companyId = localStorage.getItem("companyId");
			if (!this.companyId) {
				this.$router.push({
					path: '/home'
				});
			}
		},
		handleUploadChange: function(file, fileList) {
			this.fileList = fileList;
			this.fileName = file.name;
		},
		// 上传文件 loading为上传状态
		beforeUpload: function(file) {
			this.loadingTxt = this.$t('message.fileUploading');
			this.loading = true;
			if (file.size > 52428800) {
				this.$message.error(this.$t('message.fileBig'));
				this.loading = false;
				this.loadingTxt = '';
				return false;
			}
		},
		//分页size变化
		handleSizeChange: function(val) {
			this.pageInfo.pageSize = val;
			this.query(1);
		},
		//翻页
		handleCurrentChange: function(val) {
			this.query(parseInt(val));
		},
		// 上传
		afterUpload: function(resp) {
            this.$message.success("上传成功")
			this.token = resp.data;
			this.fileName = this.fileList[0].name;
			this.loading = false;
			this.loadingTxt = '';
			this.videoUploadPercent = 0;
			this.processVisible = false;
		},
		uploadVideoProcess(event, file, fileList) {
			this.processVisible = true;
			this.videoUploadPercent = parseInt(file.percentage.toFixed(0));
		},
		errorUpload: function(err) {
            this.$message.error("上传失败")
			console.info(err);
		},

		subPicForm() {
			let url = "";
			if (!!this.addForm.id) {
				url = "/api/media/updateMedia";
			} else {
				if (!this.token) {
					this.$message.error(this.$t('message.upFile'));
					return;
				}
				url = "/api/media/save";
			}

			if (this.addForm.type === '' || this.addForm.mediaName === '') {
				this.$message.error(this.$t('message.required'))
				return;
			}

			if (this.addForm.type === '1' || this.addForm.type === '2') {
				if (!this.extToken) {
					this.$message.error(this.$t('message.upFile'));
					return;
				}
				console.log(this.extToken)
			}

			this.saving = true;

			let params = {
				id: this.addForm.id,
				token: this.token,
				type: this.addForm.type,
				mediaName: this.addForm.mediaName,
				mediaContent: this.addForm.mediaContent,
				companyId: this.companyId,
				extToken: this.extToken
			};
			console.log(params)
			this.axios.hPost(url, params, (response) => {
				this.saving = false;
				if (response.success) {
					this.mediaVisible = false;
					this.query(1);
					this.$message.success(response.msg);
				} else {
					this.$message.error(response.msg);
				};
                this.addForm.token = '';
                this.extToken = '';
			})
		},
		// 等待结果
		query: function(pageNum) {
			//this.loading = true;
			if (!this.companyId) {
				return;
			}

			if (pageNum === 1) {
				this.mediaData = [];
			}

			let params = {
				type: this.type_query,
				companyId: this.companyId
			};
			let url = '/api/media/query?pageIndex=' + pageNum + '&pageSize=' + this.pageInfo.pageSize;
			this.axios.hPost(url, params, (response) => {
				this.showImage = true;

				if (response.list == null || response.list == [] || response.list.length === 0) {
					this.pageInfo.currentPage -= 1;
					if (pageNum !== 1) {
						this.$message.warning(this.$t('message.bottom'));
					}

					return;
				}

				if (pageNum === 1) {
					this.mediaData = response.list;
				} else {
					this.mediaData = this.mediaData.concat(response.list);
				}

				this.pageInfo.totalNum = response.totalCount;
				this.loading = false;
			});
		},
		showVideo: function(mediaPath, mediaType, capturePath) {
			if (mediaType == 0) {
				//图片
				window.open(mediaPath);
			} else {
				mediaPath = "http://api.topvision-cv.com:8081/" + mediaPath;
				capturePath = "http://api.topvision-cv.com:8081/" + capturePath;
				this.playVisible = true;
				this.playerOptions.hPoster = capturePath;
				this.playerOptions.techOrder = ['html5'];
				if (mediaPath.indexOf('.mp4') > 0) {
					this.playerOptions.sources[0].type = "video/mp4";
				} else if (mediaPath.indexOf('.ogg') > 0 || mediaPath.indexOf('.ogv') > 0) {
					this.playerOptions.sources[0].type = "video/ogg";
				} else if (mediaPath.indexOf('.webm') > 0) {
					this.playerOptions.sources[0].type = "video/webm";
				} else if (mediaPath.indexOf('.3gp') > 0) {
					this.playerOptions.sources[0].type = "video/3gp";
				} else if (mediaPath.indexOf('.flv') > 0) {
					this.playerOptions.sources[0].type = "video/x-flv";
					this.playerOptions.techOrder = ['flash'];
				} else {
					this.$message.error(this.$t('message.incorrectFormat'));
					this.playVisible = false;
					return;
				}
				this.playerOptions.sources[0].src = mediaPath;
			}
		},
		closeDialog: function() {
			this.playVisible = false;
			this.$refs.videoPlayer.player.pause();
		},

		delDialog: function(id) {
			this.mediaDelVisible = true;
			this.del_id = id;
		},

		delMedia: function() {
			this.axios.hPost('/api/media/deleteMedia', {
				id: this.del_id,
				companyId: this.companyId
			}, (response) => {
				if (response.success) {
					this.query(1);
					this.$message.success(response.msg);
				} else {
					this.$message.error(response.msg);
				}
				this.mediaDelVisible = false;
			});
		},

		modMedia: function(row) {
			this.modDisabled = true;
			this.mediaTitle = this.$t('media.modifyPictures');
			this.mediaVisible = true;
			if (this.$refs['addForm']) {
				this.$refs['addForm'].resetFields();
			}
			this.addForm.id = row.id;
			this.addForm.type = row.type;
			this.changeType(row.type);
			this.addForm.mediaName = row.mediaName;
			this.addForm.mediaContent = row.mediaContent;
		},

		isShow: function(id) {
			document.getElementById(id).style.display = "block";
		},
		isHiden: function(id) {
			document.getElementById(id).style.display = "none";
		},
		addMedia: function() {
			this.modDisabled = false;
			this.mediaTitle = this.$t('media.addPictures');
			this.mediaVisible = true;
			if (this.$refs['addForm']) {
				this.$refs['addForm'].resetFields();
				this.addForm = Object.assign(this.addForm, this.defaultData);
			}
			this.addForm.id = null;
		},
		playerReadied: function(player) {
			// seek to 10s
			console.log('example player 1 readied', player)
			//player.currentTime(10);
		},
		onPlayerLoadeddata: function(player) {
			console.log('player Loadeddata!', player);
			//this.sleep();
		},

		changeType(val) {
			if (val == 1) {
				this.extAccept = 'video/*';
				this.fileSuffix = 'mp4、3gp、flv';
			} else if (val == 2) {
				this.extAccept = 'audio/*';
				this.fileSuffix = 'mp3、wav、ogg';
			}

		},

		// 上传附件
		extAfterUpload: function(resp) {
            this.$message.success("上传成功")
			this.extToken = resp.data;
			this.loading = false;
			this.loadingTxt = '';
			this.videoUploadPercent = 0;
			this.processVisible = false;
		},
	},

	data: function() {
		return {

			//是否在加载标记
			loading: false,
			saving: false,
			videoUploadPercent: 0,
			type_query: '',
			type_save: '0',
			typeList: [],
			fileList: [],
			fileName: '',
			logoVisible: false,
			token: '',
			uuid: '',
			mediaData: [],
			noResult: false,
			showImage: false,
			loadingTxt: '',
			companyId: '',
			pageInfo: {
				currentPage: 1,
				pageSize: 12,
				totalNum: 0
			},
			addForm: {
				id: null,
				type: '',
				mediaName: '',
				mediaContent: ''
			},
			defaultData: {},
			addRules: {
				mediaName: [{
						required: true,
						message: this.$t('message.required'),
						trigger: 'blur'
					},
					{
						max: 50,
						message: this.$t('message.length50'),
						trigger: 'blur'
					},
					{
						pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/,
						message: this.$t('message.incorrectFormat'),
						trigger: 'blur'
					}
				],
				type: [{
					required: true,
					message: this.$t('message.required'),
					trigger: 'blur'
				}],
				mediaContent: [{
					max: 50,
					message: this.$t('message.length50'),
					trigger: 'blur'
				}, ]
			},

			mediaTitle: '',
			modDisabled: false,

			mediaDelVisible: false,
			del_id: '',

			errorImg: 'this.src="' + require('../../assets/logo.png') + '"',

			extAccept: 'video/*',
			extToken: '',
			fileSuffix: '',
			processVisible: false,
			playVisible: false,
			mediaVisible: false,
			formTitle: this.$t('media.videoPlay'),
			showDel: false,
			playerOptions: {
				playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
				autoplay: false, //如果true,浏览器准备好时开始回放。
				muted: false, // 默认情况下将会消除任何音频。
				loop: false, // 导致视频一结束就重新开始。
				preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
				language: 'zh-CN',
				aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
				fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
				sources: [{
					type: "video/mp4",
					src: "" //url地址
				}],
				hPoster: "", //你的封面地址
				// width: document.documentElement.clientWidth,
				//notSupportedMessage: '此视频暂无法播放，请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
				controlBar: {
					timeDivider: true,
					durationDisplay: true,
					remainingTimeDisplay: false,
					fullscreenToggle: true //全屏按钮
				}
			},
			companyList: []
		}
	}
}
